[AGC004D]Teleporter

2020-02-05
Atcoder

题意

每个点有一条出边,保证所有点都能到1

修改Min条边的终点,使得每个点都存在到1的长度为$k$的路径

题解

1必须连1自己

自下而上dep到k的时候就挂到1上

调试记录

挂上去的时候dep=-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <cstdio>
#include <algorithm>
const int maxn = 1e5 + 5;
using namespace std;
struct E{
int to, nxt;
}e[maxn];
int head[maxn], tot = 0;
void addedge(int u, int v){
e[++tot].to = v, e[tot].nxt = head[u];
head[u] = tot;
}
int a[maxn], dep[maxn], n, k, ans = 0;
void dfs(int cur, int fa){
for (int i = head[cur]; i; i = e[i].nxt){
int v = e[i].to;
dfs(v, cur);
dep[cur] = max(dep[cur], dep[v] + 1);
}
if (fa != 1 && dep[cur] == k - 1 && cur != 1) dep[cur] = -1, ++ans;
}
int main(){
scanf("%d%d%d", &n, &k, a + 1);
if (a[1] != 1) a[1] = 1, ++ans;
for (int i = 2; i <= n; i++){
scanf("%d", a + i);
addedge(a[i], i);
}
dfs(1, 0);
printf("%d\n", ans);
return 0;
}